#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define DIE_IMPLEMENTATION
#include "die.h"
#include "frame.h"

void write_frame_to_pipe(Frame *f, int pipefd)
{
    if (write(pipefd, f, sizeof(Frame)) == -1)
        die(1, "ERROR: could not write to pipe %d", pipefd);
}

void read_frame_from_pipe(Frame *f, int pipefd)
{
    if (read(pipefd, f, sizeof(Frame)) == -1)
        die(1, "ERROR: could not read from pipe %d", pipefd);
}

void print_frame(Frame *f)
{
    printf( "--------------FRAME--------------\n"
            "id = %d  ;  info = %s  ;  value = %d\n"
            "---------------------------------\n",
            f->id, f->info, f->value);
}

Frame frame_tokenize_cstr(char *line)
{
    static int id = 1;
    char *info = strtok(line, " ");
    if (!info)
    {
        fprintf(stderr, "ERROR: invalid input\n");
        return (Frame) { .id = -1 };
    }
    char *value_cstr = strtok(NULL, "");
    if (!value_cstr)
    {
        fprintf(stderr, "ERROR: invalid input\n");
        return (Frame) { .id = -1 };
    }
    int value = atoi(value_cstr);

    Frame result = (Frame) {
        .id = id++, .value = value,
    };
    strncpy(result.info, info, BUFSZ - 1);

    return result;
}
